<?php
// +----------------------------------------------------------------------
// | layerIM + Workerman + ThinkPHP5 即时通讯
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;

use think\Controller;
use think\Config;
use think\Db;
use think\File;
use app\api\controller\Upload;
use app\api\controller\Chatupload;
use app\common\model\Qrcode as QrcodeModel;
use app\common\model\WxUser as WxUserModel;
use app\common\model\Users as UsersModel;
use app\common\util\WechatThirdUtil;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\util\WechatAuthorUtil as WechatModel;
use app\common\model\Aimsgs as AimsgsModel;

class Test extends Controller
{
    protected $wechat_author_util;
    protected $author_wx_user;
    protected $qrcode_model;
    protected $config;
    protected $wx_user;
    protected $users_model;
    protected $subscribe_content;
    private  $aimsgs_model;// 数据消息表
    protected function _initialize(){
        $this->wx_user = new WxUserModel();
        $this->users_model = new UsersModel();
        $this->config = $this->wx_user->find();
        $this->author_wx_user = new AuthorWxUserModel();
        $this->aimsgs_model = new AimsgsModel();
    }

    public function butts($openid){
        $butt_now = M('csuser')->where(['status'=>1])->limit(1)->value('id');
        $update_butt = M('users')->where('openid', $openid)->update(['butt_id'=>$butt_now]);
        var_dump($update_butt);
    }

    // 从rules里面获取话术
    public function get_msg_from_rules(){
        $data = ['typeid'=>1,'msgtype'=>0];
        $result = M('aimsgs')->where($data)->find();
        dump($result);
    }
    
    // 根据openid 查询aimsgs表是否存在数据
    public function aimsgs_hasuser($openid){

        $result = $this->aimsgs_model->where(['openid'=>$openid])->select();
        dump($result) ;
        if($result){
            echo '存在用户';
        }else{
            echo '不存在用户';
        }
    }
    public function aimsgs_hasuser2($openid){
        // $this->aimsgs_model->where('openid',$openid)->find();
        $result = $this->aimsgs_model->where(['openid'=>$openid])->select();
        dump($result) ;
        if(empty($result)){
            echo '存在用户';
        }else{
            echo '不存在用户';
        }
        if(is_array($result)){
            echo '存在用户2';
        }else{
            echo '不存在用户2';
        }
    }

    public function aimsgs_hasuser3($openid){
        // $this->aimsgs_model->where('openid',$openid)->find();
        $result = $this->aimsgs_model->where(['openid'=>$openid])->find();
        dump($result) ;
        if(empty($result)){
            echo '存在用户';
        }else{
            echo '不存在用户';
        }
        if(is_array($result)){
            echo '存在用户2';
        }else{
            echo '不存在用户2';
        }
    }

    // 测试判断是否开启海草精灵
    public function isspirit(){
//        $field = 'isspirit';  field('isspirit')->
        $isspirt = $this->author_wx_user->field('isspirit')->where('appid','wx283f05dbb353b933')->select();

    }

    public function isspirit6(){
        $isspirt = $this->author_wx_user->field('isspirit')->where('appid','wx283f05dbb353b933')->select();
        dump($isspirt[0]['isspirit']);
        echo 'hello';
        echo $isspirt;  // [{"isspirit":1}]
        echo 'print_r';
        echo $isspirt[0]['isspirit'];
    }

    public function index()
    {
        return $this->fetch();
    }

    public function upload()
    {
        //$file = request()->file('file');
        //dump($file);
        return json(['code' => 1, 'data' => '', 'msg' => 'success']);
    }

    public function author(){
        $wechat = $this->config;
        $wechat_author = $this->wechat_author_util;
        $author_code = $wechat_author->getPreAuthCode();
        $redirect_uri = 'https://sn.shangning.site/index/test/savewxuser';
        //引导授权页
        $author_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$wechat['appid'].'&pre_auth_code='.$author_code['pre_auth_code'].'&redirect_uri='.$redirect_uri.'&auth_type=3';
        $this->redirect($author_url);
    }

    /**
     * @param auth_code 授权码
     * @param expires_in 过期时间
     */
    public function savewxuser($auth_code,$expires_in){
        $wechat_author = $this->wechat_author_util;
        $query_auth = $wechat_author->query_auth($auth_code);

        $wechat_info = $query_auth['authorization_info'];
        $authors = $query_auth['authorization_info']['func_info'];

        //获取授权公众号基本信息
        $base_info = $wechat_author->getAuthorizerInfo($wechat_info['authorizer_appid']);
        $wechat_base_info = $base_info['authorizer_info'];

        $data = [
            'appid'                    => $wechat_info['authorizer_appid'], //公众号appid
            'wxname'                   => $wechat_base_info['nick_name'],   //微信公众号名字
            'headerpic'                => $wechat_base_info['head_img'], //微信公众号头像
            'type'                     => $wechat_base_info['service_type_info']['id'], //微信公众号类型
            'verify_type'              => $wechat_base_info['verify_type_info'], //授权方认证类型
            'wxid'                     => $wechat_base_info['user_name'], //原始id
            'weixin'                   => $wechat_base_info['alias'], //微信号
            'qr'                       => $wechat_base_info['qrcode_url'], //二维码图片的URL
            'idc'                      => $wechat_base_info['idc'],
            'principal_name'           => $wechat_base_info['principal_name'], //公众号的主体名称
            'signature'                => $wechat_base_info['signature'], //公众号的主体名称
            'authorizer_access_token'  => $wechat_info['authorizer_access_token'], //授权方接口调用凭据
            'authorizer_expires'       => time() + $expires_in - 200, // 提前200秒过期
            'authorizer_refresh_token' => $wechat_info['authorizer_refresh_token'], //接口调用凭据刷新令牌
            'business_info'            => serialize($wechat_base_info['business_info']), //功能
            'funcscope_category'       => serialize($authors), //授权给开发者的权限集列表
        ];

        $result = $this->author_wx_user->allowfield(true)->save($data);

        if($result){
            $this->redirect(url('admin/publicnum/index'));
        }else{
            $this->error('绑定失败');
        }
    }

    public function test(){
        return $this->fetch();
    }

    public function testapi(){
        $data = $this->request->param();
        return json($data);
    }


    public function testcustomchat(){
        $wechatObj = $this->wechatObj;
        $result = $wechatObj->getSessiOnlist();
        dump($result);
    }

    //二维码
    public function qrcode(){
        $data = $this->qrcode_model->where('auid',7)->where('is_open',1)->value('media_ids');
        $media_ids = [];
        if($data){
            $media_ids = unserialize($data);
        }
        dump(1);
        dump(empty($media_ids));
    }

    public function socket(){
        // 文本加一个回车
        // $buffer1 = 'abcdefghijklmn
        // ';
        // 在php中双引号中的\n代表一个换行符，例如"\n"
        $buffer2 = '{"type":"chatMessage","data":{"mine":{"id":"20","username":"xiaoyu","avatar":"/uploads/20180425/ef30e1b96b0999f62bbe49110f42cc0f.jpg", "content":"你好啊!!"},"to":{"type":"friend","id":"21"}}}'."\n";
        // $buffer2 = '{"type":"init","id":"20","username":"xiaoyu","avatar":"/uploads/20180425/ef30e1b96b0999f62bbe49110f42cc0f.jpg","sign":"qwe"}'."\n";
        // $buffer2 = '{"type":"init","username":"xiaoyu","avatar":"/uploads/20180425/ef30e1b96b0999f62bbe49110f42cc0f.jpg","sign":"qwe"}'."\n";
        echo $buffer2;
        // 与服务端建立socket连接
        $client = stream_socket_client('tcp://127.0.0.1:8383', $errno, $errstr);
        fwrite($client, $buffer2);
    }

    public function request(){
        // $csuser = M('csuser')->where('auid',32)->find();

        $post_arr = ['content'=>'你好','openid'=>'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc','appid'=>'wx684cccbe844d934c','cs_id'=>5];
        // $post = json_encode($post_arr , JSON_UNESCAPED_UNICODE);
        $return = httpRequest('https://a.cnshuangqing.cn/receiveMsg','POST',$post_arr);
        file_put_contents('./requestMsg.log',$return);
    }

    public function login(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = M('csuser')->where('username',$data['username'])->where('password',md5($data['pwd'] . Config::get('salt')))->find();
            if($result){
                return json_encode(['status'=>1,'msg'=>'登录成功','user_info'=>$result],JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(['status'=>-1,'msg'=>'登录失败'],JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['msg'=>'你妹'],JSON_UNESCAPED_UNICODE);
        }
    }

    public function getUserInfo($appid,$openid){
        $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $result = $wechatObj->getFanInfo($openid);
        return json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function getUserInfo2($openid){
        $result = M('users')->where('openid',$openid)->find();
        return json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function sengMsgForUser(){
        // $appid = 'wx684cccbe844d934c';
        // $openid = 'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc';
        // $content = '你好!!';
        // $customerService = 'test1@JM68686866';
        if($this->request->isPost()){
            $data = $this->request->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];
            $customerService = $data['customerService'];
            $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
            $wechatObj = new WechatThirdUtil($this->config , $author_wx);
            $result = $wechatObj->appointSendMsgToOne($openid,$content,$customerService);
            if($result){
                echo '成功';
            }else{
                echo '失败';
            }
        }
    }

    public function butt(){
        $butt = M('csuser')->where('auid',33)->where('type',1)->column('id,online_butt');
        if(empty($butt)){
            return true;
        }
        $openid = 'oAtXb0RLyUGwxV25kiZ1LhiPjrM0';
        //先判断用户是否已经有对接客服
        $butt_id = M('users')->where('openid',$openid)->value('butt_id');
        if($butt_id){
            //已有对接客服,把消息传到对应客服
            $post_arr = [
                'content'=>'你好', //消息文本
                'openid'=>'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc', //用户openid
                'appid'=>'wx684cccbe844d934c', //对应公众号appid
                'cs_id'=>$butt_id, //客服id
            ];
            $return = httpRequest('https://a.cnshuangqing.cn/receiveMsg','POST',$post_arr);
            file_put_contents('./requestMsg.log',$return);
        }else{
            //初次对话
            $min_acc = min($butt);
            foreach($butt as $ko=>$vo){
                if($vo == $min_acc){
                    $butt_id = $ko; //获取对接最少客服id
                    break;
                }
            }

            $update_butt_id = M('users')->where('openid',$openid)->update(['butt_id' => $butt_id, 'create_butt_time' => time() , 'groupid' => 1]); //修改客户对接客服id
            $online_butt = M('csuser')->where('id',$butt_id)->update(['online_butt' => $butt[$butt_id]++]);//修改客服在线对接数
            if($update_butt_id && $online_butt){
                $post_arr = [
                    'content'=>'你好', //消息文本
                    'openid'=>'ouW8T0t-nV4GjaSCwbcGMSU0Vgdc', //用户openid
                    'appid'=>'wx684cccbe844d934c', //对应公众号appid
                    'cs_id'=>$butt_id, //客服id
                ];
                $return = httpRequest('https://a.cnshuangqing.cn/receiveMsg','POST',$post_arr);
                file_put_contents('./requestMsg.log',$return);
            }else{
                return json(['msg'=>'系统出错']);
            }
        }
    }

    public function getButtInfo($butt_id){
        if(!empty($butt_id)){
            $csuser_info = M('csuser')->field('pid')->where('id',$butt_id)->find();
            if($csuser_info['pid'] == 0){
                $cs_ids = M('csuser')->where('pid',$butt_id)->column('id');
                $result = $this->users_model
                        ->alias('u')
                        ->whereIn('butt_id',$cs_ids)
                        ->join('think_users_added','think_users_added.uid = u.user_id','LEFT')
                        ->order('last_butt_time desc,user_id desc')
                        ->select();
            }else{
                $result = $this->users_model
                        ->alias('u')
                        ->where('butt_id',$butt_id)
                        ->join('think_users_added','think_users_added.uid = u.user_id','LEFT')
                        ->order('last_butt_time desc,user_id desc')
                        // ->limit(500)
                        ->select();
            }
            return json(['status'=> 1,'msg'=>$result]);
        }else{
            return json(['status'=> 0,'msg'=>'错误']);
        }
    }

    public function json_de(){
        $json = '{"authorization_info":{"authorizer_appid":"wx570bc396a51b8ff8","authorizer_access_token":"10_oj8AokSO2rM9JgxdJh-4HGT6mDOH4-AFQCG9oy_I1V3gKisTUg-vBNqf3HFQ014IDlU8Tx5pMOz2cf6VgygEtbciIP6UvcEzbatjp5iCzNg_MmpSeYaMyW_SpXfEBLWLUEf_HgR3YVQl0q3KVRSeAKDBXY","expires_in":7200,"authorizer_refresh_token":"refreshtoken@@@hL3_Kr9GuyjQFiXWDCGMeABmKTqRQL7uwsFDt8El7Jk","func_info":[{"funcscope_category":{"id":1}},{"funcscope_category":{"id":15}},{"funcscope_category":{"id":4}},{"funcscope_category":{"id":7}},{"funcscope_category":{"id":2}},{"funcscope_category":{"id":3}},{"funcscope_category":{"id":11}},{"funcscope_category":{"id":6}},{"funcscope_category":{"id":5}},{"funcscope_category":{"id":8}},{"funcscope_category":{"id":13}},{"funcscope_category":{"id":9}},{"funcscope_category":{"id":10}},{"funcscope_category":{"id":12}},{"funcscope_category":{"id":17}},{"funcscope_category":{"id":18},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":19}},{"funcscope_category":{"id":22}},{"funcscope_category":{"id":23}},{"funcscope_category":{"id":24},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":25},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":26}},{"funcscope_category":{"id":27},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":30},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":31},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":33},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":35}},{"funcscope_category":{"id":36}},{"funcscope_category":{"id":37}},{"funcscope_category":{"id":40}}]}}';
        $wdata = json_decode($json,true);
        dump($wdata);
    }

    public function tag(){
        $appid = 'wx283f05dbb353b933';
        $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
        dump($author_wx);
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $tag_result = $wechatObj->createGroups('abc');
        dump($tag_result);
    }

    public function connectSql($id){
        $sqlname = 'chatlog'.$id % 10;
        // dump($sqlname);exit();
        $result = Db::connect('db_config_chatlog')->name('chatlog')->select();
        dump($result);
    }

    public function incOnlineButt(){
        $auid = 1;
        $butt = M('csuser')->where('auid',$auid)->where('status',1)->column('id,today_butt');
        dump($butt);
    }

    public function foot(){
        $openid = 'o5eJs0eu_lkCqGz9zNEFNhlnPU2E';
        M('footprint')->insert(['openid' => $openid ,'action' => 2 , 'action_time' => time()]);
    }

    public function offset(){
        $openid = 'o5eJs0cxg2b-f-DPYSz98gAXMWF0';
        $tagid_list = $this->users_model->where('openid',$openid)->value('tagid_list');
        $tagid_list_arr = unserialize($tagid_list);
        dump($tagid_list_arr);
    }

    public function uploadAudio(){
        if (!isset($_POST['audio']) && !isset($_POST['video'])) {
            echo 'PermissionDeniedError';
            return;
        }
    
        $fileName = '';
        $tempName = '';
    
        if (isset($_POST['audio'])) {
            $fileName = $_POST['audio'];
            $tempName = $_FILES['voice']['tmp_name'];
        } else {
            $fileName = $_POST['video'];
            $tempName = $_FILES['video']['tmp_name'];
        }
    
        if (empty($fileName) || empty($tempName)) {
            echo 'PermissionDeniedError';
            return;
        }
        $filePath = 'uploads/' . $fileName;
    
        // make sure that one can upload only allowed audio/video files
        $allowed = array(
            'webm',
            'wav',
            'mp4',
            'mp3',
            'ogg'
        );
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
            echo 'PermissionDeniedError';
//            continue;
        }
    
        if (!move_uploaded_file($tempName, $filePath)) {
            echo ('Problem saving file.');
            return;
        }
    
        echo ($filePath);
    }

    public function video($type){
        $appid = 'wx283f05dbb353b933';
        if($type == 1){
            $mediaId = "Vdsc_7IXMCLsKnbeM56AhmOCCvDOQxfFO98osVnu74dtv0Yx3zpxI7DzTJetIzNF";
        }else{
            $mediaId = "wGCtibZOdTCaNHlGjPxRkj_MOxtBcbW1RzYTT7PL1s9RQDEOPtVg6MYXydz0UMa8";
        }
        $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $file = $wechatObj->getTemporaryMaterial($mediaId);

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $filename = $this->savePath($upload_path);
        // 检测目录
        if (false === $this->checkPath($filename)) {
            return false;
        }
        $save_path   = '/uploads/'; 

        if (strpos($file['header']['content_type'] , 'video') !== false) {
            $name = md5(microtime(true)).'.mp4';
        } else if (strpos($file['header']['content_type'] , 'image') !== false){
            $name = md5(microtime(true)).'.jpg';
        }
        $filename_path = $filename. $name;
        $save_result = $this->saveweixinFile($filename_path,$file['body']);
        dump($save_result);
    }

    public function getMedia(){
        $appid = 'wxa46a2bdc44d05daa';
        $mediaId = "cEF2ZB3RRn9BmmEKJ4sjAmhdirDuVsNpd3MokJoI6ylXb0neobZUhWPyFtp0Ygji";
        $author_wx = M('author_wx_user')->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $file = $wechatObj->getTemporaryMaterial($mediaId);
        // dump($file);
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $filename = $this->savePath($upload_path);
        // 检测目录
        if (false === $this->checkPath(dirname($filename))) {
            return false;
        }
        $save_path   = '/uploads/'; 
        // if($file){
        $amr_name = md5(microtime(true)).'.amr';
        $name = md5(microtime(true)).'.mp3';
        $filename_path = $filename. $amr_name;
        $save_result = $this->saveweixinFile($filename_path,$file['body']);
        if($save_result){
            // $url = str_replace('\\', '/', $save_path . $filename);
            $from = $filename_path;
            $to = $filename;
            $str = "/usr/local/bin/ffmpeg -i ".$from." ".$to.$name;
            // dump($str);exit();
            system($str);
        }else{
            return json(array('status' => -1 ,'error' => 'error'));
        }
        // }
        // $chat_upload = new Chatupload;
        // $keyword_arr = $chat_upload->saveChatImage($file);
    }

    private function saveweixinFile($filename , $filecontent){
        $local_file = fopen($filename , 'w');
        if(false !== $local_file){
            if(false !== fwrite($local_file,$filecontent)){
                fclose($local_file);
                return true;
            }
        }
        return false;
    }

    public function downloadweixin($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
        return $imageAll;
    }

    public function file(){
        $rule = "date";
        $download_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $filename = $this->savePath($download_path);
        // 检测目录
        if (false === $this->checkPath($filename)) {
            return false;
        }
        return $filename;
    }

    protected function savePath($path){
        $rule = "date";
        $path = rtrim($path, DS) . DS;
        switch($rule){
            case 'date' : 
                $saveName = date('Ymd') . DS;
                break;
        }
        $filename = $path . $saveName;
        return $filename;
    }

    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }

        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            $this->error = "目录 {$path} 创建失败！";
            return false;
        }
    }

    public function menu(){
        $msg['EventKey'] = 'https://gm.00a26.cn/5fd1rgsfdrg/wf54tyhsfd/';
        $author_wx = M('author_wx_user')->where('id',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $menu = $wechatObj->getNowMenu();
        foreach($menu['menu']['button'] as $btn){
            if(isset($btn['url']) && $btn['url'] == trim($msg['EventKey'])){
                $name = $btn['name'];
            }else if (isset($btn['sub_button'])) {
                foreach($btn['sub_button'] as $sub_btn){
                    if(isset($sub_btn['url']) && $sub_btn['url'] == trim($msg['EventKey'])){
                        $name = $btn['name'];
                    }
                }
            } else {
                $name = '';
            }
        }

        dump($name);
    }

    public function uploadTime(){
        for($i = 0;$i <= 300;$i++){
            echo date('H:i:s');
            sleep(1);
        }
    }

    public function saveMessage(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $data['create_time'] = time();
            $result = Db::name('message')->strict(false)->insert($data);
            if($result){
                return json(['status' => 1 , 'msg' => 'ok']);
            }else{
                return json(['status' => -1 , 'error' => 'save error']);
            }
        }
    }

    public function showMessageList($id){
        $list = Db::name('message')->where('mid',$id)->select();
        if($list){
            return json(['status' => 1 , 'msg' => 'ok' , 'list' => $list]);
        }else{
            return json(['status' => -1 , 'error' => 'get message failed']);
        }
    }

    public function createMessage(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(isset($data['id'])) unset($data['id']);
            $data['create_time'] = time();
            $result = Db::name('message_create')->strict(false)->insert($data);
            if($result){
                return json(['status' => 1 , 'msg' => 'ok']);
            }else{
                return json(['status' => -1 , 'error' => 'save error']);
            }
        }
    }

    public function updateMessage($id){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = Db::name('message_create')->strict(false)->where('id',$id)->update($data);
            if($result){
                return json(['status' => 1 , 'msg' => 'ok']);
            }else{
                return json(['status' => -1 , 'error' => 'save error']);
            }
        }
    }

    public function LinkDetail($id){
        $list = Db::name('message_create')->where('id',$id)->find();
        $list['speech'] = html_entity_decode($list['speech']);
        if($list){
            return json(['status' => 1 , 'msg' => 'ok' , 'list' => $list]);
        }else{
            return json(['status' => -1 , 'error' => 'get message failed']);
        }
    }

    public function LinkList(){
        $list = Db::name('message_create')->select();
        if($list){
            return json(['status' => 1 , 'msg' => 'ok' , 'list' => $list]);
        }else{
            return json(['status' => -1 , 'error' => 'get message failed']);
        }
    }

    public function unifiedUpload_ok($name)
    {
        $config = [
            'size' => 2097152,
            'ext'  => 'jpg,gif,png,bmp'
        ];

        if(!($file = $this->request->file('poster'))){
            $file = $this->request->file('file');
        }


        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }

    public function unifiedUpload($name){
        $file = $this->request->file($name);
        $config = [
            'size' => 20971520,
            'ext'  => 'jpg,gif,png,bmp'
        ];

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }
    public function unifiedUpload_bk($name){
        $file = $this->request->file($name);
        if($file){
            $data = new Upload();
            $result = $data->unifiedUpload($file);
            return json($result);
        }
        return '错误';
    }

    public function reply(){
        $keyword = '你好';
        $kw_reply = M('kw_reply')->where('auid',1)->select();
        foreach($kw_reply as $reply){
            $keyword_list_info = unserialize($reply['keyword_list_info']);
            $reply_list_info = unserialize($reply['reply_list_info']);
            foreach($keyword_list_info as $keyword_info){
                if($keyword_info['match_mode'] == 'equal'){//全匹配
                    if($keyword_info['content'] == $keyword){
                        if($reply['mode'] == 'random_one'){//随机发送一条
                            $rand = array_rand($reply_list_info,1);
                            if($reply_list_info[$rand]['type'] == 'text'){//发送文本消息
                                echo $reply_list_info[$rand]['content'];
                                continue;
                            }else if($reply_list_info[$rand]['type'] == 'img'){//发送图片消息

                            }//继续判断资源文件类型
                        }else if ($reply['mode'] == 'reply_all'){//全部发送
                            foreach($reply_list_info as $reply){
                                if($reply['type'] == 'text'){
                                    echo $reply['content'];
                                    continue;
                                }else if($reply_list_info[$rand]['type'] == 'img'){//发送图片消息

                                }//继续判断资源文件类型
                            }
                        }
                    }
                }else if($keyword_info['match_mode'] == 'contain'){//半匹配
                    $is_exist = strpos($keyword,$keyword_info['content']);
                    if($is_exist !== false){
                        if($reply['mode'] == 'random_one'){//随机发送一条
                            if($reply['mode'] == 'random_one'){//随机发送一条
                                $rand = array_rand($reply_list_info,1);
                                if($reply_list_info[$rand]['type'] == 'text'){//发送文本消息
                                    echo $reply_list_info[$rand]['content'];
                                    continue;
                                }else if($reply_list_info[$rand]['type'] == 'img'){//发送图片消息

                                }//继续判断资源文件类型
                            }
                        }else if ($reply['mode'] == 'reply_all'){//全部发送
                            foreach($reply_list_info as $reply){
                                if($reply['type'] == 'text'){
                                    echo $reply['content'];
                                    continue;
                                }else if($reply_list_info[$rand]['type'] == 'img'){//发送图片消息

                                }//继续判断资源文件类型
                            }
                        }
                    }
                }
            }
        }

        echo '来到这里';
        
    }

    public function emjoiy() {
        $butt_id = 100;
        $sqlname = 'chatlog'.$butt_id % 10;
        $adb = '😱';
        $arr = [
            'type'    => 'text',
            'openid'  => 'oo5pZ09vX-6H0_uNpvEetktNcUr0', //用户openid
            'appid'   => 'wx283f05dbb353b933', //对应公众号appid
            'content' => $adb,
            'send_time' => time(), //发送时间
            'send_type' => '1002',
            'cs_id' => $butt_id,
            'pid' => 98,
            'needsend' => 1,
        ];
        Db::connect('db_config_chatlog')->name('test')->insert(['nickname' => $adb]);
    }

    public function timer_after($timer){
        $arr_data = [
            'type' => 'time_after',
            'data' => [
                'timer' => $timer,
            ],
        ];
        // 发送websocket 信息
        sendWebSocket($arr_data);
    }

    public function userList(){
        // $count = $this->users_model->where('butt_id',705)->count();
        $result = true;
        $type = 'subscribe';
        $this->subscribe_content = 'asdasd';
        if($result && $type == 'subscribe' && $this->subscribe_content){
            echo '正确';
        } else {
            echo '错误';
        }
    }
}